// 数据种子脚本 - 用于生成初始测试数据
const mongoose = require('mongoose');
const fs = require('fs');
const path = require('path');
const User = require('../models/user');
const Message = require('../models/message');
const Student = require('../models/student');
const Teacher = require('../models/teacher');
const Class = require('../models/class');
const Dormitory = require('../models/dormitory');
const Grade = require('../models/grade');
const Attendance = require('../models/attendance');
const AuditLog = require('../models/auditLog');
const passwordUtils = require('../utils/passwordUtils');
const { connectDB } = require('../config/db');
require('dotenv').config();

// 前端数据文件路径
const frontendDataPath = 'f:/NX/text-message-service/apps/web/src/data';

// 清除现有数据并生成新数据
async function seedData() {
  try {
    console.log('开始连接数据库...');
    await connectDB();
    console.log('数据库连接成功');
    
    console.log('开始清理现有数据...');
    // 按顺序清除数据，避免外键约束问题
    await Message.deleteMany({});
    await User.deleteMany({});
    await Student.deleteMany({});
    await Teacher.deleteMany({});
    await Class.deleteMany({});
    await Dormitory.deleteMany({});
    console.log('现有数据清理完成');
    
    // 导入前端JSON数据
    console.log('开始导入前端JSON数据...');
    
    // 生成测试用户数据
    const users = await generateTestUsers();
    console.log(`已创建 ${users.length} 个测试用户`);
    
  // 生成测试消息数据
  const messages = await generateTestMessages(users);
  console.log(`已创建 ${messages.length} 条测试消息`);
    
  // 导入前端数据
  await importFrontendData();
    
  console.log('✅ 数据种子生成成功！');
  console.log('\n测试账号信息：');
  console.log('1. 管理员账号:');
  console.log('   邮箱: admin@example.com');
  console.log('   密码: Admin123!');
  console.log('\n2. 普通用户账号:');
  console.log('   邮箱: user1@example.com');
  console.log('   密码: User123!');
  console.log('\n3. 教师账号:');
  console.log('   邮箱: teacher1@example.com');
  console.log('   密码: Teacher123!');
  console.log('\n4. 学生账号:');
  console.log('   邮箱: student1@example.com');
  console.log('   密码: Student123!');
  console.log('\n5. 其他测试账号请查看代码中的配置');
    
    process.exit(0);
  } catch (error) {
    console.error('❌ 数据种子生成失败:', error);
    process.exit(1);
  }
}

// 导入前端JSON数据
async function importFrontendData() {
  try {
    // 1. 导入宿舍数据
    const dormitories = await importDormitories();
    console.log(`已导入 ${dormitories.length} 个宿舍`);
    
    // 2. 导入班级数据
    const classes = await importClasses();
    console.log(`已导入 ${classes.length} 个班级`);
    
    // 3. 导入教师数据
    const teachers = await importTeachers();
    console.log(`已导入 ${teachers.length} 个教师`);
    
    // 4. 导入学生数据
    const students = await importStudents(classes, dormitories);
    console.log(`已导入 ${students.length} 个学生`);
    
    // 5. 导入成绩数据
    await importGrades(students);
    
    // 6. 导入考勤数据
    await importAttendances(students, classes);
    
    // 7. 导入审计日志数据
    await importAuditLogs();
    
    console.log('✅ 前端数据导入完成！');
  } catch (error) {
    console.error('❌ 前端数据导入失败:', error);
    throw error;
  }
}

// 导入宿舍数据
async function importDormitories() {
  const dormitoryData = JSON.parse(fs.readFileSync(path.join(frontendDataPath, 'dormitories.json'), 'utf8'));
  
  const dormitories = [];
  for (const dormData of dormitoryData) {
    const dormitory = new Dormitory({
      building: dormData.building,
      roomNumber: dormData.roomNumber,
      type: dormData.type,
      capacity: dormData.capacity,
      currentOccupancy: dormData.currentOccupancy,
      floor: dormData.floor,
      status: dormData.status,
      notes: dormData.notes,
      createdAt: new Date(dormData.createdAt),
      updatedAt: new Date(dormData.updatedAt)
    });
    await dormitory.save();
    dormitories.push(dormitory);
  }
  return dormitories;
}

// 导入班级数据
async function importClasses() {
  const classData = JSON.parse(fs.readFileSync(path.join(frontendDataPath, 'classes.json'), 'utf8'));
  
  const classes = [];
  for (const clsData of classData) {
    // 查找对应的advisor（从已导入的教师中查找）
    let advisorId = null;
    const teacher = await Teacher.findOne({ teacherId: clsData.advisorId });
    if (teacher) {
      advisorId = teacher._id;
    }
    
    const newClass = new Class({
      name: clsData.name,
      academy: clsData.academy,
      stage: clsData.stage,
      advisorId: advisorId,
      studentCount: clsData.studentCount,
      subjects: clsData.subjects,
      status: clsData.status,
      createdAt: new Date(clsData.createdAt),
      updatedAt: new Date(clsData.updatedAt)
    });
    await newClass.save();
    classes.push(newClass);
  }
  return classes;
}

// 导入教师数据
async function importTeachers() {
  const teacherData = JSON.parse(fs.readFileSync(path.join(frontendDataPath, 'teachers.json'), 'utf8'));
  
  const teachers = [];
  for (const teacherDataItem of teacherData) {
    // 创建对应的用户账号
    const hashedPassword = await passwordUtils.hashPassword('Teacher123!');
    const user = new User({
      username: teacherDataItem.teacherId.toLowerCase(),
      name: teacherDataItem.name,
      email: teacherDataItem.email,
      password: hashedPassword,
      phone: teacherDataItem.phone,
      role: 'teacher',
      status: 'active'
    });
    await user.save();
    
    // 创建教师记录
    const teacher = new Teacher({
      teacherId: teacherDataItem.teacherId,
      name: teacherDataItem.name,
      gender: teacherDataItem.gender,
      age: teacherDataItem.age,
      position: teacherDataItem.position,
      academy: teacherDataItem.academy,
      phone: teacherDataItem.phone,
      email: teacherDataItem.email,
      subjects: teacherDataItem.subjects,
      userId: user._id,
      createdAt: new Date(teacherDataItem.createdAt),
      updatedAt: new Date(teacherDataItem.updatedAt)
    });
    await teacher.save();
    teachers.push(teacher);
  }
  return teachers;
}

// 导入学生数据
async function importStudents(classes, dormitories) {
  const studentData = JSON.parse(fs.readFileSync(path.join(frontendDataPath, 'students.json'), 'utf8'));
  
  const students = [];
  for (const studentDataItem of studentData) {
    // 查找对应的班级
    let classId = null;
    const cls = classes.find(c => c.id === studentDataItem.classId);
    if (cls) {
      classId = cls._id;
    }
    
    // 随机分配一个宿舍（简化处理）
    let dormitoryId = null;
    if (dormitories.length > 0) {
      const randomDorm = dormitories[Math.floor(Math.random() * dormitories.length)];
      dormitoryId = randomDorm._id;
    }
    
    // 创建对应的用户账号
    const hashedPassword = await passwordUtils.hashPassword('Student123!');
    const user = new User({
      username: studentDataItem.studentId.toLowerCase(),
      name: studentDataItem.name,
      email: studentDataItem.email,
      password: hashedPassword,
      phone: studentDataItem.phone,
      role: 'student',
      status: 'active'
    });
    await user.save();
    
    // 创建学生记录
    const student = new Student({
      studentId: studentDataItem.studentId,
      name: studentDataItem.name,
      gender: studentDataItem.gender,
      age: studentDataItem.age,
      academy: studentDataItem.academy,
      phone: studentDataItem.phone,
      email: studentDataItem.email,
      status: studentDataItem.status,
      classId: classId,
      dormitoryId: dormitoryId,
      userId: user._id,
      createdAt: new Date(studentDataItem.createdAt),
      updatedAt: new Date(studentDataItem.updatedAt)
    });
    await student.save();
    students.push(student);
  }
  return students;
}

// 导入成绩数据
async function importGrades(students) {
  const gradeData = JSON.parse(fs.readFileSync(path.join(frontendDataPath, 'grades.json'), 'utf8'));
  
  // 检查是否有Grade模型，如果没有就创建临时集合
  let Grade;
  try {
    Grade = mongoose.model('Grade');
  } catch (e) {
    // 如果模型不存在，直接返回，因为我们不能在这里定义新模型
    console.log('Grade模型不存在，跳过成绩数据导入');
    return;
  }
  
  for (const gradeDataItem of gradeData) {
    // 查找对应的学生
    const student = students.find(s => s.studentId === gradeDataItem.studentId);
    if (student) {
      const grade = new Grade({
        studentId: student._id,
        subject: gradeDataItem.subject,
        score: gradeDataItem.score,
        examDate: new Date(gradeDataItem.examDate),
        semester: gradeDataItem.semester,
        createdAt: new Date(gradeDataItem.createdAt),
        updatedAt: new Date(gradeDataItem.updatedAt)
      });
      await grade.save();
    }
  }
  console.log(`已导入 ${gradeData.length} 条成绩记录`);
}

// 导入考勤数据
async function importAttendances(students, classes) {
  const attendanceData = JSON.parse(fs.readFileSync(path.join(frontendDataPath, 'attendances.json'), 'utf8'));
  
  // 检查是否有Attendance模型
  let Attendance;
  try {
    Attendance = mongoose.model('Attendance');
  } catch (e) {
    console.log('Attendance模型不存在，跳过考勤数据导入');
    return;
  }
  
  for (const attendanceDataItem of attendanceData) {
    // 查找对应的学生
    const student = students.find(s => s.studentId === attendanceDataItem.studentId);
    // 查找对应的班级
    const cls = classes.find(c => c.id === attendanceDataItem.classId);
    
    if (student && cls) {
      const attendance = new Attendance({
        studentId: student._id,
        classId: cls._id,
        date: new Date(attendanceDataItem.date),
        status: attendanceDataItem.status,
        notes: attendanceDataItem.notes,
        createdAt: new Date(attendanceDataItem.createdAt),
        updatedAt: new Date(attendanceDataItem.updatedAt)
      });
      await attendance.save();
    }
  }
  console.log(`已导入 ${attendanceData.length} 条考勤记录`);
}

// 导入审计日志数据
async function importAuditLogs() {
  const auditLogData = JSON.parse(fs.readFileSync(path.join(frontendDataPath, 'auditLogs.json'), 'utf8'));
  
  // 检查是否有AuditLog模型
  let AuditLog;
  try {
    AuditLog = mongoose.model('AuditLog');
  } catch (e) {
    console.log('AuditLog模型不存在，跳过审计日志导入');
    return;
  }
  
  for (const logDataItem of auditLogData) {
    // 创建审计日志对象，不直接使用可能无效的userId
    const logData = {
      action: logDataItem.action,
      entityType: logDataItem.entityType,
      entityName: logDataItem.entityName,
      timestamp: new Date(logDataItem.timestamp),
      userName: logDataItem.userName || logDataItem.userId || 'unknown',
      userRole: logDataItem.userRole || 'unknown',
      details: logDataItem.details
    };
    
    // 只有当userId是有效的ObjectId格式时才设置
    if (logDataItem.userId && mongoose.Types.ObjectId.isValid(logDataItem.userId)) {
      logData.userId = mongoose.Types.ObjectId(logDataItem.userId);
    }
    
    // 只有当entityId是有效的ObjectId格式时才设置
    if (logDataItem.entityId && mongoose.Types.ObjectId.isValid(logDataItem.entityId)) {
      logData.entityId = mongoose.Types.ObjectId(logDataItem.entityId);
    }
    
    const log = new AuditLog(logData);
    await log.save();
  }
  console.log(`已导入 ${auditLogData.length} 条审计日志`);
}

// 生成测试用户
async function generateTestUsers() {
  const userData = [
    {
      username: 'admin',
      name: '管理员',
      email: 'admin@example.com',
      password: 'Admin123!',
      phone: '13800138000',
      role: 'admin',
      status: 'active'
    },
    {
      username: 'user1',
      name: '普通用户1',
      email: 'user1@example.com',
      password: 'User123!',
      phone: '13900139001',
      role: 'student',
      status: 'active'
    },
    {
      username: 'user2',
      name: '普通用户2',
      email: 'user2@example.com',
      password: 'User123!',
      phone: '13900139002',
      role: 'student',
      status: 'active'
    },
    // 教师账号
    {
      username: 'teacher1',
      name: '张老师',
      email: 'teacher1@example.com',
      password: 'Teacher123!',
      phone: '13900139005',
      role: 'teacher',
      status: 'active',
      subject: '数学'
    },
    {
      username: 'teacher2',
      name: '李老师',
      email: 'teacher2@example.com',
      password: 'Teacher123!',
      phone: '13900139006',
      role: 'teacher',
      status: 'active',
      subject: '语文'
    },
    // 学生账号
    {
      username: 'student1',
      name: '小明',
      email: 'student1@example.com',
      password: 'Student123!',
      phone: '13900139007',
      role: 'student',
      status: 'active',
      grade: '三年级',
      class: '二班'
    },
    {
      username: 'student2',
      name: '小红',
      email: 'student2@example.com',
      password: 'Student123!',
      phone: '13900139008',
      role: 'student',
      status: 'active',
      grade: '四年级',
      class: '一班'
    },
    {
      username: 'student3',
      name: '小华',
      email: 'student3@example.com',
      password: 'Student123!',
      phone: '13900139009',
      role: 'student',
      status: 'active',
      grade: '五年级',
      class: '三班'
    },
    // 其他状态用户
    {
      username: 'disabled',
      name: '已禁用用户',
      email: 'disabled@example.com',
      password: 'User123!',
      phone: '13900139010',
      role: 'student',
      status: 'suspended'
    },
    {
      username: 'pending',
      name: '待审核用户',
      email: 'pending@example.com',
      password: 'User123!',
      phone: '13900139011',
      role: 'student',
      status: 'inactive'
    }
  ];
  
  // 加密密码并创建用户
  const users = [];
  for (const data of userData) {
    const hashedPassword = await passwordUtils.hashPassword(data.password);
    const user = new User({
      ...data,
      password: hashedPassword
    });
    users.push(await user.save());
  }
  
  return users;
}

// 生成测试消息
async function generateTestMessages(users) {
  const messageTemplates = [
    '你好，这是一条测试消息！',
    '很高兴认识你！',
    '请问你有什么可以帮助我的吗？',
    '谢谢你的回复！',
    '这条消息将用于测试系统功能。',
    '请确认你已收到此消息。',
    '这是一条重要通知。',
    '测试消息，请勿回复。',
    '系统测试进行中...',
    '祝工作愉快！'
  ];
  
  const messageTypes = ['text', 'notification', 'system'];
  
  // 创建消息
  const messages = [];
  const admin = users.find(u => u.role === 'admin');
  const activeUsers = users.filter(u => u.status === 'active');
  
  // 生成用户间的消息
  for (let i = 0; i < 20; i++) {
    const sender = activeUsers[Math.floor(Math.random() * activeUsers.length)];
    let receiver;
    do {
      receiver = activeUsers[Math.floor(Math.random() * activeUsers.length)];
    } while (sender._id.toString() === receiver._id.toString());
    
    // 根据用户角色设置正确的发送者类型
    let senderType = 'User';
    if (sender.role === 'student') {
      senderType = 'Student';
    } else if (sender.role === 'teacher') {
      senderType = 'Teacher';
    }
    
    // 根据用户角色设置正确的接收者类型
    let receiverType = 'User';
    if (receiver.role === 'student') {
      receiverType = 'Student';
    } else if (receiver.role === 'teacher') {
      receiverType = 'Teacher';
    }
    
    const message = new Message({
      senderId: sender._id,
      senderType: senderType,
      receiverId: receiver._id,
      receiverType: receiverType,
      content: messageTemplates[Math.floor(Math.random() * messageTemplates.length)],
      type: messageTypes[Math.floor(Math.random() * messageTypes.length)],
      status: 'sent',
      isRead: Math.random() > 0.5 // 50%概率已读
    });
    messages.push(await message.save());
  }
  
  // 从管理员向所有用户发送系统通知
  for (const user of activeUsers) {
    if (user._id.toString() !== admin._id.toString()) {
      let receiverType = 'User';
      if (user.role === 'student') {
        receiverType = 'Student';
      } else if (user.role === 'teacher') {
        receiverType = 'Teacher';
      }
      
      const systemMessage = new Message({
        senderId: admin._id,
        senderType: 'User',
        receiverId: user._id,
        receiverType: receiverType,
        content: `欢迎使用文本消息系统，${user.name}！这是一条系统通知。`,
        type: 'system',
        status: 'sent',
        isRead: false
      });
      messages.push(await systemMessage.save());
    }
  }
  
  return messages;
}

// 执行种子脚本
seedData();